package com.example.demo.dao.impl;

import com.example.demo.domain.base.BaseEntity;
import com.example.demo.vo.PageRequest;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.stereotype.Component;

/**
 * 创建DetachedCriteria工厂
 *
 * @author Jack
 * @version V1.0
 * @Description: 创建DetachedCriteria工厂
 * @date 2018/1/12 10:22
 */
@Component
public class DetachedCriteriaFactory {

    /**
     * 创建DetachedCriteria
     *
     * @param
     * @return
     * @throws
     * @Description: 创建DetachedCriteria
     * @author Jack
     * @date 2018/1/12
     */
    public <E extends BaseEntity> DetachedCriteria buildDetachedCriteria(Class<E> clazz, Criterion[] criterionArray) {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(clazz);
        this.addCriterion(detachedCriteria, criterionArray);
        // 将查询出的字段映射到实体类的字段中，貌似没啥用，注释掉也可以
//        detachedCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        return detachedCriteria;
    }

    private void addCriterion(DetachedCriteria detachedCriteria, Criterion[] criterionArray) {
        if (null != criterionArray && criterionArray.length > 0) {
            for (Criterion criterion : criterionArray) {
                detachedCriteria.add(criterion);
            }
        }
    }

    public <E extends BaseEntity> DetachedCriteria buildDetachedCriteriaWithOrder(Class<E> clazz, PageRequest pageRequest,
                                                                                  Criterion[] criterionArray) {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(clazz);
        this.addCriterion(detachedCriteria, criterionArray);
        this.addOrder(detachedCriteria, pageRequest.getOrder());
        return detachedCriteria;
    }

    private void addOrder(DetachedCriteria detachedCriteria, Order[] orderArray) {
        if (null != orderArray && orderArray.length > 0) {
            for (Order order : orderArray) {
                detachedCriteria.addOrder(order);
            }
        }
    }
}
